package com.manager.common.tcp.client.handler;

import com.manager.common.tcp.client.TcpClient;
import com.manager.common.tcp.decode.impl.BusinessDecode;
import com.manager.common.tcp.encode.impl.HeartEncode;
import com.manager.common.tcp.constant.TcpDataType;
import com.manager.common.tcp.decode.BaseDecode;
import com.manager.common.tcp.decode.DecodeFactory;
import com.manager.common.utils.DataTools;
import com.manager.common.utils.DateTools;
import com.manager.common.utils.SocketByteConvertUtils;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;


public class TcpClientDataHandler extends SimpleChannelInboundHandler<byte[]> {

    private static byte[] lastTimeResidue = new byte[0];

    private int starIndex = 0;
    private byte[] remainBytes;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, byte[] data) throws Exception {
        //暂时不考虑粘包问题
        //0x2766
        DataTools.setTcpConnected(true);
        ByteBuf buf = Unpooled.buffer();
        if (remainBytes != null) {
            buf.writeBytes(remainBytes);
        }
        buf.writeBytes(data);
        byte[] starMarkBytes = null;
        while (buf.readableBytes() >= 7) {
            if (starMarkBytes == null) {
                starMarkBytes = new byte[2];
                buf.readBytes(starMarkBytes);
            } else {
                starMarkBytes[0] = starMarkBytes[1];
                starMarkBytes[1] = buf.readByte();
            }
            String starMark = SocketByteConvertUtils.bytesToHexString(starMarkBytes);
            if (!"2766".equals(starMark)) {
                continue;
            }

            byte[] typeBytes = new byte[1];
            buf.readBytes(typeBytes);
            int type = SocketByteConvertUtils.bigEndian1ByteToInt(typeBytes[0]);
            TcpDataType tcpDataType = TcpDataType.getTcpDataType(type);
            System.out.println(DateTools.getCurrentDateString("yyyy-MM-dd HH:mm:ss") + " " + tcpDataType.getCode() + " : " + tcpDataType.getDesc());
            if (type == TcpDataType.HEARTBEAT.getCode()) {
                buf.readerIndex(buf.readerIndex() + 4);
                starMarkBytes = null;
                continue;
            }
            byte[] dataLenBytes = new byte[4];
            buf.readBytes(dataLenBytes);
            int dataLen = SocketByteConvertUtils.bigEndian4ByteToInt(dataLenBytes);

            if (dataLen > buf.readableBytes()) {
                buf.readerIndex(buf.readerIndex() - 7);
                break;
            }

            //获取一帧数据
            byte[] contentFrameData = new byte[dataLen];
            buf.readBytes(contentFrameData);
            byte[] frameData = new byte[contentFrameData.length + 7];
            SocketByteConvertUtils.mergeByteArray(frameData, starMarkBytes, typeBytes, dataLenBytes, contentFrameData);

            BusinessDecode businessDecode = (BusinessDecode) DecodeFactory.getDecode(frameData);
            System.out.println(businessDecode.getTcpDataType().getDesc() + " : " + businessDecode.getContent());
            if (businessDecode.getTcpDataType().equals(TcpDataType.CONTAINER_MANAGER)) {
                TcpClient.getInstance().getDisposeReportCommandQueue().put(businessDecode);
            } else {
                TcpClient.getInstance().getReceiptQueue().put(businessDecode);
            }
           /* if(baseDecode.getTcpDataType().equals(TcpDataType.RECEIPT)){
                BusinessDecode businessDecode = (BusinessDecode) baseDecode;
                System.out.println("回执：" + businessDecode.getContent());
                JSONObject jsonObject = JSONObject.fromObject(businessDecode.getContent());
                TcpClient.getInstance().getReceiptQueue().put(businessDecode);
            }else {
                BusinessDecode businessDecode = (BusinessDecode) baseDecode;
                String content = businessDecode.getContent();
                System.out.println(content);
                if(StringUtils.isNotEmpty(content)){
                    //发送信息到展示端

                }
            }*/
            starMarkBytes = null;
        }

        remainBytes = new byte[buf.readableBytes()];
        buf.readBytes(remainBytes);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        DataTools.setTcpConnected(true);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        DataTools.setTcpConnected(false);
    }

}
